<template>
  <div ref="chartRef" class="chart"></div>
</template>

<script setup>
import { onMounted, ref, onBeforeUnmount, inject, watch } from 'vue'
import * as echarts from 'echarts'
// 导入JSON数据文件
import visitData from '@/data/visitTrendData.json'

const chartRef = ref(null)
let chartInstance
let handleResize
let resizeTimer = null
let isDestroyed = false

// 获取屏幕尺寸信息
const screenSize = inject('screenSize', ref({
  width: window.innerWidth,
  height: window.innerHeight,
  isMobile: window.innerWidth <= 768,
  isTablet: window.innerWidth > 768 && window.innerWidth <= 1024,
  isDesktop: window.innerWidth > 1024
}))

// 监听屏幕尺寸变化
watch(screenSize, (newSize) => {
  if (chartInstance && !isDestroyed) {
    setTimeout(() => {
      handleResize();
    }, 100);
  }
}, { deep: true });

// 从JSON数据生成图表配置
const getChartOption = () => ({
  title: { 
    text: visitData.title || '访问趋势', 
    textStyle: { 
      color: '#00eaff', 
      fontSize: 16, 
      fontWeight: 'bold' 
    },
  },
  xAxis: { 
    type: 'category', 
    data: visitData.xAxisData, 
    axisLine: { lineStyle: { color: '#00eaff' } } 
  },
  yAxis: { 
    type: 'value', 
    axisLine: { lineStyle: { color: '#00eaff' } },
    // 如果有单位信息则显示
    ...(visitData.unit && { 
      axisLabel: { 
        formatter: `{value} ${visitData.unit}` 
      } 
    })
  },
  series: [{
    data: visitData.seriesData,
    type: 'line',
    smooth: true,
    itemStyle: { color: '#00eaff' }
  }],
  grid: { 
    top: 40, 
    left: 40, 
    right: 20, 
    bottom: 30,
    containLabel: true
  }
})

// 暴露 resize 方法给父组件
defineExpose({
  handleResize: () => {
    if (chartInstance && !isDestroyed) {
      handleResize();
    }
  }
})

onMounted(() => {
  isDestroyed = false;
  if (chartRef.value) {
    chartInstance = echarts.init(chartRef.value)
    
    chartInstance.setOption(getChartOption())

    // 防抖处理的resize函数
    handleResize = () => {
      if (isDestroyed) return;
      
      clearTimeout(resizeTimer)
      resizeTimer = setTimeout(() => {
        if (chartInstance && !isDestroyed) {
          try {
            chartInstance.resize()
          } catch (error) {
            console.warn('Resize error:', error);
          }
        }
      }, 300)
    }
    window.addEventListener('resize', handleResize)
  }
})

onBeforeUnmount(() => {
  isDestroyed = true;
  
  if (handleResize) {
    window.removeEventListener('resize', handleResize)
  }
  clearTimeout(resizeTimer)
  
  if (chartInstance) {
    try {
      chartInstance.clear();
      chartInstance.dispose();
    } catch (error) {
      console.warn('清理图表时出现警告:', error);
    } finally {
      chartInstance = null;
    }
  }
})
</script>

<style scoped>
.chart {
  width: 100%;
  height: 100%;
  min-height: 300px;
}
</style>